/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
import _ from 'lodash';
import CryptoJS from 'crypto-js';
import sha256 from 'crypto-js/sha256';
import { useConfigState } from './useConfigState';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
export const useConfigProcessor = () => {
	const { configGroupInfo, currentGroupIndex, editorRef } = useConfigState();
	const processEditorData = () => {
		const editorValue = editorRef.current?.handleSave() ?? '';
		const base64Data = btoa(unescape(encodeURIComponent(editorValue)));
		const hashDigest = sha256(editorValue).toString(CryptoJS.enc.Hex);

		_.assign(configGroupInfo[currentGroupIndex], {
			Sha256: hashDigest,
			ConfigData: base64Data
		});
	};
	return { processEditorData };
};
export const useGroupManager = () => {
	const { processEditorData } = useConfigProcessor();
	const {
		configGroupInfo,
		setConfigGroupInfo,
		setCurrentGroupIndex,
		setCodeEdit,
		setCodeVersion,
		activeContent,
		isConfigModified
	} = useConfigState();

	const handleClick = (index: number) => {
		if (isConfigModified) {
			processEditorData();
			setConfigGroupInfo(configGroupInfo);
		}

		setCurrentGroupIndex(index);
		setCodeEdit(Utf8.stringify(Base64.parse(activeContent[index].ConfigData)));
		setCodeVersion(activeContent[index].ConfigNodeList[0].ConfigVersion);
	};

	return {
		handleClick
	};
};
